<template>
  <view>
    <view class="head">
      <u-navbar :leftIcon="goods_id?'arrow-leftward':' '" :rightText="editing? '完成' : '編輯' "
                @rightClick="rightClick" :placeholder='true'
                title="購物車" @leftClick="back">
      </u-navbar>
    </view>
    <view class="empty" v-if="show==false">
      <image
          src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F82%2F40%2F596fa6dc00bb4_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633499781&t=d37222e32213957ddbdd01d62e071309"
          mode="widthFix" style="width: 400rpx;"></image>
      <view class="empty-text">空空如也的購物</view>
      <view class="empty-button" @click="goshopping">去選購</view>
    </view>
    <view v-if="show==true" style="padding-bottom: 144rpx;">
      <view class="goods-detail" v-for="(item,index) in cardlist" :key="item.goods_id">
        <view class=" detail-left">
          <view class="goods-left">
            <u-checkbox-group @change="selected(item)">
              <label>
                <u-checkbox activeColor="#645AED" shape="circle" class="selected" color="#555555"
                            :checked="item.flag"/>
                <text></text>
              </label>
            </u-checkbox-group>
            <view class="goods-img" @click="$store.dispatch('toDetails',item.goods_id)">
              <image :src="getFirstImageLink(item.goods_images)" mode="aspectFit"></image>
              <!-- <image :src="item.goodsImage" style="width: 150rpx;height: 140rpx;"></image> -->
            </view>
          </view>
          <view class="size">
            <view class="goods-title" @click="$store.dispatch('toDetails',item.goods_id)">{{ item.goods_name }}</view>
            <view class="center">
              {{ item.attr_value }}
            </view>
            <view class="bottom">
              <text class="goods-price">MOP {{ item.goods_price }}</text>
              <view class="detail-right">
                <!-- 	<text class="subtract" @click="reduce(item)">-</text>
                  <text class="num">{{item.num}}</text>
                  <text @click="add(item)" class="add">+</text> -->
                <view class="stepper">
                  <view class="stepper-btn" @click="reduce(item)">
                    <image src="@/static/images/quantity_reduce.png" mode=""></image>
                  </view>
                  <u--input style="width: 100rpx;" inputAlign="center"  border="none" v-model="item.goods_number" fontSize="26rpx"  @change="leavinput(item)" @blur="leavinput(item)"
                            type="number">
                  </u--input>
                  <!--                  <view class="stepper-value">{{ item.goods_number }}</view>-->
                  <view class="stepper-btn" @click="add(item)">
                    <image src="@/static/images/quantity_add.png" mode=""></image>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="end">
      <view class="end-left">
        <u-checkbox-group @change="selectgoods()">
          <label style="display: flex;align-items: center;">
            <u-checkbox activeColor="#645AED" shape="circle" :checked="allchecked"/>
            全選
          </label>
        </u-checkbox-group>

      </view>
      <view v-if="!editing" class="end-right">
        <view class="end-price">
          <view>
            總計：
            <text style="font-size: 30rpx;font-weight: bold;color: #4949C3;">MOP {{ totalPrices }}</text>
          </view>
          <view style="font-size: 22rpx;font-weight: 500;color: #333333;">
            共{{ totalNums }}件
          </view>
        </view>
        <view class="btn" @click="Tosubmit">
          結算
        </view>
      </view>
      <view v-else class="end-right">
        <view class="btn red" @click="delegood">
          刪除
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getcart_list,
} from '@/network/api/user.js'
import {
  deletecart,
  changecart
} from '@/network/api/cart.js'
import {
  mapState,
  mapActions
} from 'vuex'

export default {
  data() {
    return {
      goods_id: "",
      editing: false,
      show: true,
      allchecked: false,
      checked: false,
      cardlist: [],
      totalNums: 0,
      totalPrices: 0
    }
  },
  onLoad() {
    console.log(111)
  },
  computed: {
    ...mapState({
      islogin: state => state.user.islogin,
      company: state => state.user.company,
      userinfo: state => state.user.userinfo,
      cartnums: state => state.user.cartnums,
      quotenums: state => state.user.quotenums,
    })
  },
  onShow() {
    this.goods_id = uni.getStorageSync('goods_id') || ""
    this.allchecked = false
    // if(this.islogin){
    this.getCart()
    // }
    this.totalNum()
    this.totalPrice()
  },
  onReady() {
  },
  methods: {
    leavinput(item) {
      console.log(item)
      if (item.goods_number < 1) {
        item.goods_number = 1
        return uni.showToast({
          title: '最少不能低于一件商品',
          icon: 'none'
        })
      }
      let data = {
        rec_id: item.rec_id,
        goods_number: item.goods_number,
        goods_attr_id: item.goods_attr_id || ''
      }
      this.cartchange(data)

    },
    back() {
      if (!this.goods_id) {
        return
      }
      this.$store.dispatch('toDetails', this.goods_id)
    },
    togooddetail(item) {
      console.log(item);
    },
    async delegood() {
      if (!this.isAnyItemSelected()) {
        uni.showToast({
          title: "请至少选择一项商品",
          icon: "none"
        });
        return;
      }
      let toDeleteList = [];
      let toKeepList = [];
      this.cardlist.forEach(item => {
        if (item.flag) {
          // 商品被选择，加入要删除的列表
          toDeleteList.push(item);
        } else {
          // 商品未被选择，加入不要删除的列表
          toKeepList.push(item);
        }
      });
      this.cardlist = toKeepList;
      let rec_id = toDeleteList.map(item => item.rec_id);
      let data = {
        rec_id: rec_id
      }
      const res = await deletecart(data)
      if (res.data.code == 1) {
        uni.showToast({
          title: "删除成功",
          icon: "none"
        });
        this.getCart()
      }

    },
    async getCart() {
      if (!this.islogin) {
        this.cardlist = []
        return
      }
      const res = await getcart_list()
      this.cardlist = res.data.cart
      // 假设this.carlist是一个包含车辆信息的数组
      this.cardlist.forEach((item) => {
        item.flag = false;
      });
      console.log(this.cardlist, 'getCart');
    },
    isAnyItemSelected() {
      return this.cardlist.some(item => item.flag);
    },

    Tosubmit() {

      console.log(this.cardlist);
      if (!this.isAnyItemSelected()) {
        uni.showToast({
          title: "请至少选择一项商品",
          icon: "none"
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/shopping/order/index?cartlist=${JSON.stringify(this.cardlist.filter(item => item.flag))}&totalNum=${this.totalNums}&totalPrice=${this.totalPrices}`
      });
      this.allchecked = false
      this.checked = false
      this.cardlist.forEach((item, index) => {
        item.flag = false
      })


    },
    rightClick() {
      this.editing = !this.editing;
      this.totalPrice()
      this.totalNum()
    },
    goshopping() {
      uni.navigateTo({
        url: '../contact/contact'
      })
    },
    selected(item) {
      console.log(item);
      item.flag = !item.flag
      this.allchecked = this.cardlist.every(item => item.flag);
      this.totalPrice()
      this.totalNum()

    },
    selectgoods() {
      this.allchecked = !this.allchecked
      if (this.allchecked) {
        this.cardlist.forEach(item => {
          // this.checked = true
          item.flag = true
        })
      } else {
        this.cardlist.forEach(item => {
          // this.checked = false
          item.flag = false
        })
      }
      this.totalPrice()
      this.totalNum()
    },
    async cartchange(data) {
      const res = await changecart(data)
      console.log(res.data.code)
      if (res.data.code == 2) {
        this.getCart()
        uni.showToast({
          title: "商品庫存不足，請聯繫管理員",
          icon: "none"
        });
      }
    },
    reduce(item) {
      let num = item.goods_number
      if (num > 1) {
        num -= 1
      } else if (num = 1) {
        uni.showToast({
          title: "该宝贝不能减少了哟~"
        })
      }
      item.goods_number = num
      let data = {
        rec_id: item.rec_id,
        goods_number: item.goods_number,
        goods_attr_id: item.goods_attr_id || ''
      }
      this.totalNum()
      this.totalPrice()
      this.cartchange(data)
    },
    add(item) {
      let num = item.goods_number
      item.goods_number = num + 1
      let data = {
        rec_id: item.rec_id,
        goods_number: item.goods_number,
        goods_attr_id: item.goods_attr_id || ''
      }
      this.totalNum()
      this.totalPrice()
      this.cartchange(data)

    },
    totalNum() {
      this.totalNums = 0;
      this.cardlist.map(item => {
        item.flag ? this.totalNums += item.goods_number : this.totalNums += 0
      })
    },
    totalPrice() {
      this.totalPrices = 0;
      this.cardlist.map(item => {
        item.flag ? this.totalPrices += item.goods_number * item.goods_price : this.totalPrices += 0
      })
      this.totalPrices = this.totalPrices.toFixed(2);
    }
  },
  // computed: {
  // 	totalNum() {
  // 		let totalNum = 0;
  // 		console.log('123123');
  // 		this.cardlist.map(item => {
  // 			item.flag ? totalNum += item.goods_number : totalNum += 0
  // 		})
  // 		return totalNum
  // 	},

  // 	totalPrice() {
  // 		console.log(1231312);
  // 		let totalPrice = 0;
  // 		this.cardlist.map(item => {
  // 			item.flag ? totalPrice += item.goods_number * item.goods_price : totalPrice += 0
  // 		})
  // 		return totalPrice
  // 	}
  // }
}
</script>

<style lang="scss">
page {
  background: #f5f6f9;
}

.goods {
  line-height: 80rpx;
  background-color: #FFFFFF;

  &-detail {
    // display: flex;
    padding: 32rpx;
    // margin: 0 32rpx;
    background-color: #fff;
    justify-content: space-between;
    border-bottom: 1rpx solid #F1F1F1;
    align-items: center;

    .detail-left {
      display: flex;

      .goods-left {
        display: flex;
        align-items: center;


        .goods-img {
          margin-left: 24rpx;
          width: 180rpx;
          height: 180rpx;
          background: #FFFFFF;
          border: 1rpx solid #DEDEDE;
          border-radius: 30rpx;
          display: flex;
          justify-content: center;
          align-items: center;

          image {
            max-width: 90%;
            max-height: 90%;
          }
        }
      }
    }

    .size {
      flex: 999;
      display: flex;
      justify-content: space-between;
      flex-direction: column;
      margin-left: 30rpx;

      .center {
        font-size: 22rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #999999;
        margin-top: 8rpx;
      }

      .bottom {
        margin-top: 22rpx;
        display: flex;
        align-items: center;
        justify-content: space-between
      }

      .goods-title {
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
      }

      .goods-price {
        font-size: 28rpx;
        font-family: PingFang SC;
        font-weight: bold;
        color: #4949C3;
      }
    }

    .detail-right {
      .stepper {
        display: flex;
        // align-items: center;
        vertical-align: middle;
        align-items: center;
        .stepper-value {
          margin: 0 20rpx;
          font-size: 24rpx;
          line-height: 43rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #333333;
        }

        .stepper-btn {
          image {
            width: 44rpx;
            height: 44rpx;
          }
        }
      }

      text {
        width: 50rpx;
        line-height: 50rpx;
        text-align: center;
        display: inline-block;
        background-color: #F7F7F7;
        margin-right: 10rpx;
      }

      .add {
        color: #FA4305;
        border-radius: 10rpx 30rpx 30rpx 10rpx;
        margin-right: 20rpx;
      }

      .subtract {
        border-radius: 30rpx 10rpx 10rpx 30rpx;
      }
    }
  }
}

.empty {

  position: relative;
  top: 220rpx;
  text-align: center;
  display: flex;
  align-items: center;
  flex-direction: column;

  &-text {
    color: #808080;
    margin-bottom: 50rpx;
  }

  &-button {
    width: 300rpx;
    height: 90rpx;
    color: orange;
    border: 1rpx solid orange;
    text-align: center;
    line-height: 90rpx;
    border-radius: 48rpx;
  }
}

.end {
  width: 100%;
  height: 110rpx;
  background-color: #fff;
  position: fixed;
  // bottom: 0;//ios
  bottom: var(--window-bottom);
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &-left {
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #333333;
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx;

    .end-flex {
      display: flex;
      align-items: center;
    }
  }

  &-right {
    margin-right: 32rpx;
    display: flex;

    .end-price {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: flex-end;

    }

    .btn {
      margin-left: 20rpx;
      text-align: center;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: bold;
      line-height: 0rpx;
      color: #FFFFFF;
      width: 170rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #645AED;
      border-radius: 30rpx;
    }

    .red {
      background: #ED0000;
    }

  }
}
</style>
